<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Cache;
use think\helper\Str;

class Remit extends Base
{
    protected $type = [
        'examine_time' => 'timestamp'
    ];

    protected function user(): object
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,photo');
    }

    protected function getAccountAttr($value): string
    {
        return get_pay_way($value);
    }

    protected function getPayWayAttr($value): string
    {
        return get_pay_way($value);
    }

    protected function getStatusNameAttr($value, $data): string
    {
        return getExamineStatus($data['status']);
    }

    public static function _save($param, $options): array
    {
        parent::startTrans();
        try {
            if (empty($param['status'])) {
                throw new \Exception('请选择审核类型');
            }
            $info = parent::where(['id' => $param['id'], 'status' => 1])->find();
            if (empty($info)) {
                throw new \Exception('该申请不存在或已审核');
            }
            if ($param['status'] == 2) {
                $info->reject_msg = '';
                Target::Account()->basics($info->uid, $info->getData('account'), $info->amount, '充值', '+')
                    ->createNormal();
                $content = '您的充值申请通过审核，已发放至您的账户余额，请注意查收。';
                UserNotify::add(1, $info->uid, '充值到账', $content);
                $msg = '通过充值申请，标识ID【' . $param['id'] . '】，会员【' . $info->user->id . '】【' . $info->user->code . '】';
            } else {
                $info->reject_msg = $param['reject_msg'];
                $content = '您的充值申请已被驳回，请查看原因。';
                UserNotify::add(1, $info->uid, '充值驳回', $content);
                $msg = '驳回充值申请，标识ID【' . $param['id'] . '】，会员【' . $info->user->id . '】【' . $info->user->code . '】，驳回原因【' . $param['reject_msg'] . '】';
            }
            $info->status = $param['status'];
            $info->admin_id = $options['admin']->id;
            $info->admin_name = $options['admin']->admin_name;
            $info->examine_time = time();
            $info->save();
            Logs::adds($msg, $options['admin']->id, $options['admin']->admin_name);
            parent::commit();

            return ['code' => 1, 'msg' => '审核成功'];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function batchPass($param, $admin, $options): array
    {
        parent::startTrans();
        try {
            $list = parent::where(['status' => 1])->whereIn('id', $param['id'])->select();
            if ($list->isEmpty()) {
                throw new \Exception('未查询到待审核的数据，请检查！');
            }
            $new_ids = [];
            foreach ($list as $item) {
                Target::Account()->basics($item->uid, $item->getData('account'), $item->amount, '充值', '+')
                    ->createNormal();
                $new_ids[] = $item->id;
                $content = '您的充值申请通过审核，已发放至您的账户余额，请注意查收。';
                UserNotify::add(1, $item->uid, '充值到账', $content);
            }
            if ($new_ids) {
                parent::update([
                    'status' => 2,
                    'examine_time' => time(),
                    'admin_id' => $admin->id,
                    'admin_name' => $admin->admin_name
                ], ['id' => $new_ids]);
                $msg = '批量通过充值申请，标识ID【' . implode(',', $new_ids) . '】';
                Logs::adds($msg, $admin->id, $admin->admin_name);
            }
            parent::commit();

            return ['code' => 1, 'msg' => '批量通过成功'];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function batchReject($param, $admin, $options): array
    {
        parent::startTrans();
        try {
            $list = parent::where(['status' => 1])->whereIn('id', $param['id'])->select();
            if ($list->isEmpty()) {
                throw new \Exception('未查询到待审核的数据，请检查！');
            }
            $new_ids = [];
            foreach ($list as $item) {
                $new_ids[] = $item->id;
                $content = '您的充值申请已被驳回，请查看原因。';
                UserNotify::add(1, $item->uid, '充值驳回', $content);
            }
            if ($new_ids) {
                parent::update([
                    'status' => 3,
                    'reject_msg' => $param['batchReject'],
                    'examine_time' => time(),
                    'admin_id' => $admin->id,
                    'admin_name' => $admin->admin_name
                ], ['id' => $new_ids]);
                $msg = '批量驳回充值申请，标识ID【' . implode(',', $new_ids) . '】，驳回原因【' . $param['batchReject'] . '】';
                Logs::adds($msg, $admin->id, $admin->admin_name);
            }
            parent::commit();

            return ['code' => 1, 'msg' => '批量驳回成功'];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function add($param, $user, $system): array
    {
        try {
            if (empty($system['remit_open'])) {
                throw new \Exception('充值功能已关闭');
            }
            if ($system['remit_min'] > $param['amount']) {
                throw new \Exception('最低充值金额：' . $system['remit_min']);
            }
            if (!empty($system['remit_bs'])) {
                if ($param['amount'] % $system['remit_bs'] != 0) {
                    throw new \Exception('充值倍数：' . $system['remit_bs']);
                }
            }
            $sn = 'R' . date('YmdHis') . Str::random(6, 1) . $user->id;
            parent::create([
                'sn' => $sn,
                'uid' => $user->id,
                'account' => $param['account'],
                'pay_way' => $param['pay_way'],
                'amount' => $param['amount'],
                'images' => $param['images']
            ]);
            $tips = [
                'type' => 'remit',
                'title' => '充值管理',
                'msg' => '您有新的充值申请，请及时处理<br/>会员编号：' . $user->code . '<br/>充值金额：' . $param['amount'] . '<br/>',
            ];
            Cache::set('tips', $tips);

            return ['code' => 1, 'msg' => '申请已提交，请耐心等待审核'];
        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}